package co.edu.unal.satacredito.database.administration.ejb;

import java.net.UnknownHostException;
import java.util.List;
import javax.ejb.Stateless;

import org.bson.types.ObjectId;

import com.mongodb.MongoException;
import co.edu.unal.satacredito.database.administration.exceptions.DAOException;
import co.edu.unal.satacredito.database.administration.singleton.SingletonDataStore;
import co.edu.unal.satacredito.database.connection.AdministratorDatastoreFactory;
import co.edu.unal.satacredito.database.dao.AdministratorMongoDao;
import co.edu.unal.satacredito.database.entity.Administrator;
import co.edu.unal.satacredito.database.entity.exceptions.NonexistentEntityException;
import co.edu.unal.satacredito.database.entity.exceptions.PreexistingEntityException;

/**
 * Session Bean implementation class AdministrationDaoEJB
 */
@Stateless
public class AdministrationDaoEJB implements AdministrationDaoEJBRemote, AdministrationDaoEJBLocal {

	private AdministratorMongoDao daoA;
	
	/**
	 * Default constructor.
	 * 
	 * @throws DAOException
	 */
	public AdministrationDaoEJB() throws DAOException{
		this.daoA = new AdministratorMongoDao(SingletonDataStore.getInstance()
				.getDataStore());
	}
	
	@Override
	public void createAdministrator(Administrator user) throws DAOException{
		try {
			daoA.create(user);
		} catch (PreexistingEntityException e) {
			throw new DAOException(e.getMessage());
		}
	}
	
	@Override
	public void editAdministrator(Administrator user) throws DAOException{
		try {
			daoA.update(user.getId(), user);
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}

	@Override
	public void deleteAdministrador(String id) throws DAOException{
		try {
			daoA.delete(new ObjectId(id));
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}

	@Override
	public Administrator findByUser(String user) throws DAOException {
		try {
			return daoA.findByUser(user);
			
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}
	
	@Override
	public List<Administrator> findAllUsers() throws DAOException {
		try {
			List<Administrator> findAll = daoA.findAll();
			return findAll;
			
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}
	
}
